package cn.lg.soar.boot.fc.controller;

import cn.lg.soar.boot.fc.entity.FormCollect;
import cn.lg.soar.boot.fc.entity.ProcessApply;
import cn.lg.soar.boot.fc.entity.TenancyRoom;
import cn.lg.soar.boot.fc.service.FormCollectService;
import cn.lg.soar.boot.fc.service.ProcessApplyService;
import cn.lg.soar.boot.fc.service.ProcessService;
import cn.lg.soar.common.model.HttpResult;
import cn.lg.soar.common.model.PageQuery;
import cn.lg.soar.common.model.PageResult;
import cn.lg.soar.core.annotations.IdempotentByParam;
import cn.lg.soar.core.annotations.constraints.group.Create;
import cn.lg.soar.core.annotations.constraints.group.Update;
import cn.lg.soar.database.base.controller.BaseController;
import cn.lg.soar.database.query.SqueryWapper;
import cn.lg.soar.mvc.enums.ControllerConst;
import cn.lg.soar.database.query.QueryParams;
import cn.lg.soar.mvc.annotations.Log;
import cn.lg.soar.system.api.manager.AccountManager;
import cn.lg.soar.system.api.model.AuthUser;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import cn.lg.soar.database.base.controller.BaseController;
import cn.lg.soar.boot.fc.entity.ProcessExamine;
import cn.lg.soar.boot.fc.service.ProcessExamineService;

/**
 * 流程审批表
 * @author ZhuanZ（无密码）
 * @since 2025-01-15
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@Api(tags = "流程审批表")
@Validated
@RestController
@RequestMapping("fc/processExamine")
public class ProcessExamineController extends BaseController<ProcessExamine, ProcessExamineService> {
    @Autowired
    private AccountManager accountManager;
    @Resource
    private FormCollectService formCollectService;
    @Resource
    private ProcessExamineService processExamineService;
    @Resource
    private ProcessService processService;
    private SqueryWapper<FormCollect> formCollectWapper;
    private SqueryWapper<cn.lg.soar.boot.fc.entity.Process> processWapper;

    @Override
    protected Serializable getId(ProcessExamine entity) {
        return entity.getId();
    }

    @Log(value = "新增流程审批表", data = "#p0", dataId = "#$r.data")
    @IdempotentByParam("#p0")
    @ApiOperation(value = ControllerConst.CREATE_NAME)
    @RequestMapping(path = "create", method = RequestMethod.POST)
    public HttpResult<Serializable> create(@RequestBody @Validated(Create.class) ProcessExamine data) {
        return super.createResult(data);
    }

    @Log(value = "修改流程审批表", data = "#p0", dataId = "#p0.id")
    @ApiOperation(value = ControllerConst.UPDATE_NAME)
    @RequestMapping(path = "update", method = RequestMethod.POST)
    public HttpResult<Void> update(@RequestBody @Validated(Update.class) ProcessExamine data) {
        return super.updateResult(data);
    }

    @Log(value = "删除流程审批表", data = "#p0")
    @ApiOperation(value = ControllerConst.REMOVE_NAME, notes = "根据 id 删除")
    @RequestMapping(path = "remove", method = RequestMethod.POST)
    public HttpResult<Void> remove(@RequestBody List<Long> ids) {
        return super.removeResult(ids);
    }

    @ApiOperation(value = ControllerConst.DETAIL_NAME, notes = "根据 ID 获取一条数据")
    @RequestMapping(path = "detail", method = RequestMethod.GET)
    public HttpResult<ProcessExamine> detail(@RequestParam Long id) {
        return super.detailResult(id);
    }

    @ApiOperation(value = ControllerConst.QUERY_NAME, notes = "多功能查询（分页、列表、统计）")
    @RequestMapping(path = "query", method = RequestMethod.GET)
    public HttpResult<PageResult<ProcessExamine>> query(PageQuery pageQuery, QueryParams params){
        params.setFields(new ArrayList<>());
        AuthUser user = accountManager.getUser();
        System.out.println("===========user="+user.getId()+"==="+user.getUsername());
        List<String> f = params.getF();
        f.add("approverId-eq~"+user.getId());
        f.add("result-eq~0");

        StringBuilder collectIds = new StringBuilder();
        if (formCollectWapper == null) {
            formCollectWapper = new SqueryWapper<>(FormCollect.class);
        }
//        QueryWrapper<FormCollect> collectWrapper = Wrappers.query();
//        List<String> collectF = new ArrayList<>();
//        collectF.add("visibleRange-eq~0");
//        formCollectWapper.setWhere(collectF, collectWrapper);
//        List<FormCollect> list1 = formCollectService.list(collectWrapper);
//        if(!list1.isEmpty()) {
//            for (FormCollect formCollect : list1) {
//                collectIds.append("~").append(formCollect.getId());
//            }
//            f.add("collectId-in"+collectIds);
//        }else{
//            f.add("collectId-eq~0");
//        }

        params.setF(f);
        PageResult<ProcessExamine> pageResult = super.queryResult(pageQuery, params).getData();
        for (ProcessExamine processExamine : pageResult.getList()) {
            FormCollect collect = formCollectService.getById(processExamine.getCollectId());
            if(collect != null){
                processExamine.setExtend1(String.valueOf(collect.getVisibleRange()));
            }
        }
        return HttpResult.data(pageResult);
    }

    @Log(value = "导出流程审批表")
    @ApiOperation(value = ControllerConst.EXPORT_NAME)
    @RequestMapping(path = "export", method = RequestMethod.GET)
    public void exports(String filename, QueryParams params, HttpServletResponse resp){
        super.exportExcel(filename, params, resp);
    }

    @Log(value = "导入流程审批表")
    @ApiOperation(value = ControllerConst.IMPORT_NAME)
    @RequestMapping(path = "import", method = RequestMethod.POST)
    public HttpResult<Void> imports(HttpServletRequest req){
        return super.importExcel(req);
    }

    @Operation(summary = "审核 @author lhp")
    @PostMapping("/examine")
    public HttpResult<Void> processExamine(@RequestBody @Valid ProcessExamine updateForm) {
        return processExamineService.processExamine(updateForm);
    }

    @ApiOperation(value = "租房审批查询", notes = "多功能查询（分页、列表、统计）")
    @RequestMapping(path = "tenancyQuery", method = RequestMethod.GET)
    public HttpResult<PageResult<ProcessExamine>> tenancyQuery(PageQuery pageQuery, QueryParams params){
        if (processWapper == null) {
            processWapper = new SqueryWapper<>(cn.lg.soar.boot.fc.entity.Process.class);
        }
        QueryWrapper<cn.lg.soar.boot.fc.entity.Process> wrapper = Wrappers.query();
        List<String> processF = new ArrayList<>();
        processF.add("examineType-eq~1");
        processWapper.setWhere(processF, wrapper);
        List<cn.lg.soar.boot.fc.entity.Process> list = processService.list(wrapper);

        params.setFields(new ArrayList<>());
        AuthUser user = accountManager.getUser();
        System.out.println("===========user="+user.getId()+"==="+user.getUsername());
        List<String> f = params.getF();
        f.add("approverId-eq~"+user.getId());
        f.add("result-eq~0");

        StringBuilder processIds = new StringBuilder();
//        StringBuilder collectIds = new StringBuilder();
//        if (formCollectWapper == null) {
//            formCollectWapper = new SqueryWapper<>(FormCollect.class);
//        }
//        QueryWrapper<FormCollect> collectWrapper = Wrappers.query();
//        List<String> collectF = new ArrayList<>();
//        collectF.add("visibleRange-eq~0");
//        formCollectWapper.setWhere(collectF, collectWrapper);
//        List<FormCollect> list1 = formCollectService.list(collectWrapper);
        if(!list.isEmpty()) {
            for (cn.lg.soar.boot.fc.entity.Process process : list) {
                processIds.append("~").append(process.getId());
            }
            f.add("processId-in"+processIds);
        }else{
            f.add("processId-eq~0");
        }

        params.setF(f);
        PageResult<ProcessExamine> pageResult = super.queryResult(pageQuery, params).getData();
        for (ProcessExamine processExamine : pageResult.getList()) {
            FormCollect collect = formCollectService.getById(processExamine.getCollectId());
            if(collect != null){
                processExamine.setExtend1(String.valueOf(collect.getVisibleRange()));
            }
        }
        return HttpResult.data(pageResult);
    }

    @ApiOperation(value = "退房审批查询", notes = "多功能查询（分页、列表、统计）")
    @RequestMapping(path = "outTenancyQuery", method = RequestMethod.GET)
    public HttpResult<PageResult<ProcessExamine>> outTenancyQuery(PageQuery pageQuery, QueryParams params){
        if (processWapper == null) {
            processWapper = new SqueryWapper<>(cn.lg.soar.boot.fc.entity.Process.class);
        }
        QueryWrapper<cn.lg.soar.boot.fc.entity.Process> wrapper = Wrappers.query();
        List<String> processF = new ArrayList<>();
        processF.add("examineType-eq~2");
        processWapper.setWhere(processF, wrapper);
        List<cn.lg.soar.boot.fc.entity.Process> list = processService.list(wrapper);

        params.setFields(new ArrayList<>());
        AuthUser user = accountManager.getUser();
        System.out.println("===========user="+user.getId()+"==="+user.getUsername());
        List<String> f = params.getF();
        f.add("approverId-eq~"+user.getId());
        f.add("result-eq~0");

        StringBuilder processIds = new StringBuilder();
        if(!list.isEmpty()) {
            for (cn.lg.soar.boot.fc.entity.Process process : list) {
                processIds.append("~").append(process.getId());
            }
            f.add("processId-in"+processIds);
        }else{
            f.add("processId-eq~0");
        }

        params.setF(f);
        PageResult<ProcessExamine> pageResult = super.queryResult(pageQuery, params).getData();
        for (ProcessExamine processExamine : pageResult.getList()) {
            FormCollect collect = formCollectService.getById(processExamine.getCollectId());
            if(collect != null){
                processExamine.setExtend1(String.valueOf(collect.getVisibleRange()));
            }
        }
        return HttpResult.data(pageResult);
    }

    @ApiOperation(value = "维修审批查询", notes = "多功能查询（分页、列表、统计）")
    @RequestMapping(path = "repairQuery", method = RequestMethod.GET)
    public HttpResult<PageResult<ProcessExamine>> repairQuery(PageQuery pageQuery, QueryParams params){
        if (processWapper == null) {
            processWapper = new SqueryWapper<>(cn.lg.soar.boot.fc.entity.Process.class);
        }
        QueryWrapper<cn.lg.soar.boot.fc.entity.Process> wrapper = Wrappers.query();
        List<String> processF = new ArrayList<>();
        processF.add("examineType-eq~3");
        processWapper.setWhere(processF, wrapper);
        List<cn.lg.soar.boot.fc.entity.Process> list = processService.list(wrapper);

        params.setFields(new ArrayList<>());
        AuthUser user = accountManager.getUser();
        System.out.println("===========user="+user.getId()+"==="+user.getUsername());
        List<String> f = params.getF();
        f.add("approverId-eq~"+user.getId());
        f.add("result-eq~0");

        StringBuilder processIds = new StringBuilder();
        if(!list.isEmpty()) {
            for (cn.lg.soar.boot.fc.entity.Process process : list) {
                processIds.append("~").append(process.getId());
            }
            f.add("processId-in"+processIds);
        }else{
            f.add("processId-eq~0");
        }

        params.setF(f);
        PageResult<ProcessExamine> pageResult = super.queryResult(pageQuery, params).getData();
        for (ProcessExamine processExamine : pageResult.getList()) {
            FormCollect collect = formCollectService.getById(processExamine.getCollectId());
            if(collect != null){
                processExamine.setExtend1(String.valueOf(collect.getVisibleRange()));
            }
        }
        return HttpResult.data(pageResult);
    }

    @ApiOperation(value = "转租审批查询", notes = "多功能查询（分页、列表、统计）")
    @RequestMapping(path = "subletQuery", method = RequestMethod.GET)
    public HttpResult<PageResult<ProcessExamine>> subletQuery(PageQuery pageQuery, QueryParams params){
        if (processWapper == null) {
            processWapper = new SqueryWapper<>(cn.lg.soar.boot.fc.entity.Process.class);
        }
        QueryWrapper<cn.lg.soar.boot.fc.entity.Process> wrapper = Wrappers.query();
        List<String> processF = new ArrayList<>();
        processF.add("examineType-eq~4");
        processWapper.setWhere(processF, wrapper);
        List<cn.lg.soar.boot.fc.entity.Process> list = processService.list(wrapper);

        params.setFields(new ArrayList<>());
        AuthUser user = accountManager.getUser();
        System.out.println("===========user="+user.getId()+"==="+user.getUsername());
        List<String> f = params.getF();
        f.add("approverId-eq~"+user.getId());
        f.add("result-eq~0");

        StringBuilder processIds = new StringBuilder();
        if(!list.isEmpty()) {
            for (cn.lg.soar.boot.fc.entity.Process process : list) {
                processIds.append("~").append(process.getId());
            }
            f.add("processId-in"+processIds);
        }else{
            f.add("processId-eq~0");
        }

        params.setF(f);
        PageResult<ProcessExamine> pageResult = super.queryResult(pageQuery, params).getData();
        return HttpResult.data(pageResult);
    }

    @ApiOperation(value = "用户审批查询", notes = "多功能查询（分页、列表、统计）")
    @RequestMapping(path = "clientUserQuery", method = RequestMethod.GET)
    public HttpResult<PageResult<ProcessExamine>> clientUserQuery(PageQuery pageQuery, QueryParams params){
        if (processWapper == null) {
            processWapper = new SqueryWapper<>(cn.lg.soar.boot.fc.entity.Process.class);
        }
        QueryWrapper<cn.lg.soar.boot.fc.entity.Process> wrapper = Wrappers.query();
        List<String> processF = new ArrayList<>();
        processF.add("examineType-eq~5");
        processWapper.setWhere(processF, wrapper);
        List<cn.lg.soar.boot.fc.entity.Process> list = processService.list(wrapper);

        params.setFields(new ArrayList<>());
        AuthUser user = accountManager.getUser();
        System.out.println("===========user="+user.getId()+"==="+user.getUsername());
        List<String> f = params.getF();
        f.add("approverId-eq~"+user.getId());
        f.add("result-eq~0");

        StringBuilder processIds = new StringBuilder();
        if(!list.isEmpty()) {
            for (cn.lg.soar.boot.fc.entity.Process process : list) {
                processIds.append("~").append(process.getId());
            }
            f.add("processId-in"+processIds);
        }else{
            f.add("processId-eq~0");
        }

        params.setF(f);
        PageResult<ProcessExamine> pageResult = super.queryResult(pageQuery, params).getData();
        for (ProcessExamine processExamine : pageResult.getList()) {
            FormCollect collect = formCollectService.getById(processExamine.getCollectId());
            if(collect != null){
                processExamine.setExtend1(String.valueOf(collect.getVisibleRange()));
            }
        }
        return HttpResult.data(pageResult);
    }

}